package cn.backpackerxl.web.util;

import cn.backpackerxl.web.annotation.GetMapping;
import cn.backpackerxl.web.annotation.PostMapping;
import cn.backpackerxl.web.annotation.RequestMapping;
import cn.backpackerxl.web.model.ControllerMethod;
import cn.backpackerxl.web.model.Servlet;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author:backpackerxl CreateTime:2022/4/17
 * FileName:HandlerController
 **/
public class HandlerController {
    private static Set<Servlet> handlerServlet(Set<Class<?>> contr) {
        Set<Servlet> servletSet = new HashSet<>();
        for (Class<?> clazz : contr) {
            Servlet servlet = new Servlet();
            servlet.setClazz(clazz);
            if (clazz.isAnnotationPresent(RequestMapping.class)) {
                servlet.setPath(clazz.getDeclaredAnnotation(RequestMapping.class).value().substring(1));
            }
            List<ControllerMethod> controllerMethods = new ArrayList<>();
            try {
                Method[] methods = clazz.getDeclaredMethods();
                for (Method method : methods) {
                    String path = "";
                    if (method.isAnnotationPresent(GetMapping.class)) {
                        path = method.getDeclaredAnnotation(GetMapping.class).value().substring(1);
                    } else if (method.isAnnotationPresent(PostMapping.class)) {
                        path = method.getDeclaredAnnotation(PostMapping.class).value().substring(1);
                    }
                    controllerMethods.add(new ControllerMethod(method, path));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            servlet.setControllerMethod(controllerMethods);
            servletSet.add(servlet);
        }
        return servletSet;
    }

    public static Set<Servlet> handlerRequest(Set<Class<?>> contr) {
        return handlerServlet(contr);
    }
}
